<template>
  <div class="modern-login-wrap">
    <div class="login-bg">
      <div class="bg-shapes">
        <div class="shape shape-1"></div>
        <div class="shape shape-2"></div>
        <div class="shape shape-3"></div>
      </div>
    </div>

    <div class="login-container">
      <div class="login-box">
        <div class="login-header">
          <div class="logo-wrapper">
            <img src="@/assets/logo.png" alt="Logo" class="logo" />
          </div>
          <h2>欢迎回来</h2>
          <p>登录以访问ERP管理系统</p>
        </div>

        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          @submit.prevent="handleLogin"
        >
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              size="large"
              prefix-icon="User"
              class="modern-input"
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              size="large"
              prefix-icon="Lock"
              show-password
              @keyup.enter="handleLogin"
              class="modern-input"
            />
          </el-form-item>

          <el-form-item>
            <div class="login-options">
              <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
              <el-link type="primary" :underline="false" @click="showForgotPassword">忘记密码？</el-link>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              size="large"
              class="login-btn modern-btn"
              :loading="loading"
              @click="handleLogin"
              style="width: 100%"
            >
              {{ loading ? '登录中...' : '登录' }}
            </el-button>
          </el-form-item>
        </el-form>

        <div class="login-footer">
          <p>默认账号：<strong>admin</strong> / <strong>123456</strong></p>
        </div>
      </div>
    </div>

    <!-- 忘记密码对话框 -->
    <el-dialog
      v-model="forgotPasswordVisible"
      title="忘记密码"
      width="480px"
      :close-on-click-modal="false"
    >
      <el-steps :active="resetStep" align-center finish-status="success" class="reset-steps">
        <el-step title="验证身份" />
        <el-step title="验证码" />
        <el-step title="重置密码" />
      </el-steps>

      <!-- 步骤1：验证身份 -->
      <el-form
        v-if="resetStep === 0"
        ref="identityFormRef"
        :model="resetForm"
        :rules="identityRules"
        label-width="90px"
        class="reset-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="resetForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
          />
        </el-form-item>
        <el-form-item label="邮箱/手机" prop="contact">
          <el-input
            v-model="resetForm.contact"
            placeholder="请输入注册时的邮箱或手机号"
            prefix-icon="Message"
          />
        </el-form-item>
        <el-form-item>
          <div class="form-tips">
            <el-icon><InfoFilled /></el-icon>
            <span>我们将向您的邮箱或手机发送验证码</span>
          </div>
        </el-form-item>
      </el-form>

      <!-- 步骤2：输入验证码 -->
      <el-form
        v-if="resetStep === 1"
        ref="codeFormRef"
        :model="resetForm"
        :rules="codeRules"
        label-width="90px"
        class="reset-form"
      >
        <el-form-item label="验证码" prop="code">
          <div class="code-input-wrapper">
            <el-input
              v-model="resetForm.code"
              placeholder="请输入6位验证码"
              maxlength="6"
              prefix-icon="Lock"
            />
            <el-button
              :disabled="countdown > 0"
              @click="sendVerificationCode"
              type="primary"
              plain
            >
              {{ countdown > 0 ? `${countdown}秒后重发` : '重新发送' }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <div class="form-tips success">
            <el-icon><SuccessFilled /></el-icon>
            <span>验证码已发送至 {{ maskContact(resetForm.contact) }}</span>
          </div>
        </el-form-item>
      </el-form>

      <!-- 步骤3：重置密码 -->
      <el-form
        v-if="resetStep === 2"
        ref="passwordFormRef"
        :model="resetForm"
        :rules="passwordRules"
        label-width="90px"
        class="reset-form"
      >
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="resetForm.newPassword"
            type="password"
            placeholder="请输入新密码（6-20位）"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="resetForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item>
          <div class="password-strength">
            <span>密码强度：</span>
            <div class="strength-bar">
              <div
                class="strength-fill"
                :class="passwordStrength.level"
                :style="{ width: passwordStrength.width }"
              ></div>
            </div>
            <span class="strength-text" :class="passwordStrength.level">
              {{ passwordStrength.text }}
            </span>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleResetCancel">取消</el-button>
          <el-button v-if="resetStep > 0" @click="handleResetPrev">上一步</el-button>
          <el-button
            type="primary"
            :loading="resetLoading"
            @click="handleResetNext"
          >
            {{ resetStep === 2 ? '完成重置' : '下一步' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { InfoFilled, SuccessFilled } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 定义emits，向父组件传递登录事件
const emit = defineEmits(['login'])

const loginFormRef = ref()
const loading = ref(false)

const loginForm = reactive({
  username: 'admin',
  password: '123456',
  rememberMe: false
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    await loginFormRef.value.validate()
    loading.value = true

    // 调用登录接口
    const response = await userStore.login(loginForm)

    // 判断 code === 200
    if (response.code === 200) {
      ElMessage.success(response.msg || '登录成功')
      
      // 触发登录成功事件
      emit('login', response)
      
      // 获取重定向路径
      const redirect = route.query.redirect
      
      // 如果有重定向路径，跳转到该路径，否则跳转到 dashboard
      if (redirect && redirect !== '/login') {
        router.push(decodeURIComponent(redirect))
      } else {
        router.push('/dashboard')
      }
    } else {
      ElMessage.error(response.msg || '登录失败')
    }
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error(error.message || '网络请求失败，请重试')
  } finally {
    loading.value = false
  }
}

// ==================== 忘记密码功能 ====================
const forgotPasswordVisible = ref(false)
const resetStep = ref(0)
const resetLoading = ref(false)
const countdown = ref(0)
let countdownTimer = null

const identityFormRef = ref()
const codeFormRef = ref()
const passwordFormRef = ref()

const resetForm = reactive({
  username: '',
  contact: '',
  code: '',
  newPassword: '',
  confirmPassword: ''
})

// 验证规则
const identityRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  contact: [
    { required: true, message: '请输入邮箱或手机号', trigger: 'blur' },
    {
      pattern: /^(1[3-9]\d{9}|[\w.-]+@[\w.-]+\.\w+)$/,
      message: '请输入有效的邮箱或手机号',
      trigger: 'blur'
    }
  ]
}

const codeRules = {
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码为6位', trigger: 'blur' }
  ]
}

const passwordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== resetForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 密码强度计算
const passwordStrength = computed(() => {
  const pwd = resetForm.newPassword
  if (!pwd) return { level: 'weak', text: '弱', width: '0%' }

  let strength = 0
  if (pwd.length >= 8) strength += 1
  if (pwd.length >= 12) strength += 1
  if (/\d/.test(pwd)) strength += 1
  if (/[a-z]/.test(pwd)) strength += 1
  if (/[A-Z]/.test(pwd)) strength += 1
  if (/[!@#$%^&*(),.?":{}|<>]/.test(pwd)) strength += 1

  if (strength <= 2) {
    return { level: 'weak', text: '弱', width: '33%' }
  } else if (strength <= 4) {
    return { level: 'medium', text: '中', width: '66%' }
  } else {
    return { level: 'strong', text: '强', width: '100%' }
  }
})

// 显示忘记密码对话框
const showForgotPassword = () => {
  forgotPasswordVisible.value = true
  resetStep.value = 0
  Object.assign(resetForm, {
    username: '',
    contact: '',
    code: '',
    newPassword: '',
    confirmPassword: ''
  })
}

// 掩码显示联系方式
const maskContact = (contact) => {
  if (!contact) return ''
  if (contact.includes('@')) {
    const [name, domain] = contact.split('@')
    return name.substring(0, 2) + '***@' + domain
  } else {
    return contact.substring(0, 3) + '****' + contact.substring(7)
  }
}

// 发送验证码
const sendVerificationCode = async () => {
  try {
    ElMessage.success('验证码已发送，请查收')
    countdown.value = 60
    countdownTimer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(countdownTimer)
        countdownTimer = null
      }
    }, 1000)
  } catch (error) {
    ElMessage.error('验证码发送失败，请重试')
  }
}

// 下一步
const handleResetNext = async () => {
  try {
    if (resetStep.value === 0) {
      await identityFormRef.value.validate()
      resetLoading.value = true
      setTimeout(() => {
        resetLoading.value = false
        resetStep.value = 1
        sendVerificationCode()
      }, 500)
    } else if (resetStep.value === 1) {
      await codeFormRef.value.validate()
      resetLoading.value = true
      setTimeout(() => {
        resetLoading.value = false
        if (resetForm.code === '123456') {
          resetStep.value = 2
          ElMessage.success('验证码正确')
        } else {
          ElMessage.error('验证码错误，测试验证码为：123456')
        }
      }, 500)
    } else if (resetStep.value === 2) {
      await passwordFormRef.value.validate()
      resetLoading.value = true
      setTimeout(() => {
        resetLoading.value = false
        ElMessage.success('密码重置成功！请使用新密码登录')
        forgotPasswordVisible.value = false
        if (countdownTimer) {
          clearInterval(countdownTimer)
          countdownTimer = null
          countdown.value = 0
        }
      }, 800)
    }
  } catch (error) {
    console.error('操作失败:', error)
  }
}

// 上一步
const handleResetPrev = () => {
  resetStep.value--
}

// 取消
const handleResetCancel = () => {
  forgotPasswordVisible.value = false
  resetStep.value = 0
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
    countdown.value = 0
  }
}
</script>

<style scoped>
.modern-login-wrap {
  position: relative;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-bg {
  position: absolute;
  inset: 0;
  overflow: hidden;
}

.bg-shapes {
  position: absolute;
  inset: 0;
}

.shape {
  position: absolute;
  border-radius: 50%;
  filter: blur(80px);
  opacity: 0.3;
  animation: float 20s infinite ease-in-out;
}

.shape-1 {
  width: 400px;
  height: 400px;
  background: #ff6b9d;
  top: -100px;
  left: -100px;
  animation-delay: 0s;
}

.shape-2 {
  width: 350px;
  height: 350px;
  background: #4ecdc4;
  bottom: -100px;
  right: -100px;
  animation-delay: 5s;
}

.shape-3 {
  width: 300px;
  height: 300px;
  background: #ffe66d;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  animation-delay: 10s;
}

@keyframes float {
  0%, 100% {
    transform: translate(0, 0);
  }
  25% {
    transform: translate(30px, -30px);
  }
  50% {
    transform: translate(-20px, 20px);
  }
  75% {
    transform: translate(20px, 30px);
  }
}

.login-container {
  position: relative;
  z-index: 1;
  width: 100%;
  max-width: 420px;
  padding: 20px;
}

.login-box {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  padding: 40px;
}

.login-header {
  text-align: center;
  margin-bottom: 32px;
}

.logo-wrapper {
  margin-bottom: 16px;
}

.logo {
  height: 50px;
}

.login-header h2 {
  margin: 0 0 8px;
  font-size: 24px;
  font-weight: 700;
  color: #303133;
}

.login-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.login-form {
  margin-top: 20px;
}

.modern-input :deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.modern-input :deep(.el-input__wrapper):hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.modern-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.modern-btn {
  border-radius: 8px;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  transition: all 0.3s ease;
}

.modern-btn:hover {
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.5);
  transform: translateY(-2px);
}

.login-footer {
  text-align: center;
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.login-footer p {
  margin: 0;
  color: #909399;
  font-size: 12px;
}

/* ==================== 忘记密码对话框样式 ==================== */
.reset-steps {
  margin-bottom: 30px;
}

.reset-form {
  margin-top: 30px;
  padding: 0 20px;
}

.form-tips {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 15px;
  background: rgba(64, 158, 255, 0.1);
  border: 1px solid rgba(64, 158, 255, 0.3);
  border-radius: 6px;
  color: #409eff;
  font-size: 13px;
}

.form-tips.success {
  background: rgba(103, 194, 58, 0.1);
  border-color: rgba(103, 194, 58, 0.3);
  color: #67c23a;
}

.code-input-wrapper {
  display: flex;
  gap: 10px;
}

.code-input-wrapper .el-input {
  flex: 1;
}

.code-input-wrapper .el-button {
  min-width: 110px;
}

.password-strength {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 13px;
  color: #606266;
}

.strength-bar {
  flex: 1;
  height: 6px;
  background: #e4e7ed;
  border-radius: 3px;
  overflow: hidden;
}

.strength-fill {
  height: 100%;
  border-radius: 3px;
  transition: all 0.3s ease;
}

.strength-fill.weak {
  background: linear-gradient(90deg, #f56c6c, #ff8080);
}

.strength-fill.medium {
  background: linear-gradient(90deg, #e6a23c, #f0b960);
}

.strength-fill.strong {
  background: linear-gradient(90deg, #67c23a, #85ce61);
}

.strength-text {
  min-width: 30px;
  font-weight: 600;
}

.strength-text.weak {
  color: #f56c6c;
}

.strength-text.medium {
  color: #e6a23c;
}

.strength-text.strong {
  color: #67c23a;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>

